package org.zyj.io.example.case2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

/**
 * 描述
 *
 * @author zhouyijin
 * @date 2022-01-17 15:53:04
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        System.out.println("msg 类型=" + msg.getClass());
        System.out.println("客户端地址: " + ctx.channel().remoteAddress());
        if (msg instanceof HttpRequest request) {
            final String uri = request.uri();
            if ("/favicon.ico".equals(uri)) {
                return;
            }
            ByteBuf content = Unpooled.copiedBuffer("hello this is server", StandardCharsets.UTF_8);
            final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    content);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
